package com.study.forumsystemproject.utils;

import com.study.forumsystemproject.common.Result;
import com.study.forumsystemproject.common.ResultCode;
import com.study.forumsystemproject.exception.ApplicationException;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * program: forum-system-project
 * <p>
 * description: url工具类
 * <p>
 * author: xiaoxie
 * <p>
 * create: 2024-08-19 20:32
 **/
@Slf4j
public class UrlUtil {

        private static final int MAX_ATTEMPTS = 5;
        private static final int TIMEOUT_MS = 5000;

        /**
         * 检查URL是否可达。
         * @param urlStr URL地址
         * @return 如果URL可达返回true，否则返回false
         */
        public static boolean isURLReachable(String urlStr) {
            if (urlStr == null || urlStr.isEmpty()) {
                return false;
            }
            for (int attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
                try {
                    URL url = new URL(urlStr);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    con.setConnectTimeout(TIMEOUT_MS);
                    con.setReadTimeout(TIMEOUT_MS);

                    int responseCode = con.getResponseCode();
                    con.disconnect(); // 总是断开连接

                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        return true;
                    }
                } catch (IOException e) {
                    // 可以记录日志或处理异常
                    log.warn(e.getMessage());
                    throw new ApplicationException(Result.fail(e.getMessage()));
                }
            }
            return false;
        }
}
